package com.yanqu.xiuxian.crosssystem.manger.elementalbonds.logic;

import com.yanqu.xiuxian.crosssystem.manger.elementalbonds.data.ElementalBondsGameData;
import com.yanqu.xiuxian.crosssystem.manger.elementalbonds.entity.ElementalBondsBlock;

import java.util.*;

public class ElementalBondsFrameLogic {

    public static List<ElementalBondsBlock> randomFramePos(ElementalBondsGameData elementalBondsGameData, Random random, int num) {

        if (num <= 0) {
            return new ArrayList<>();
        }

        // 把非边缘的格子添加进去
        Set<ElementalBondsBlock> elementalBondsBlockSet = new HashSet<>();
        List<List<ElementalBondsBlock>> blockList = elementalBondsGameData.getBlockList();
        for (int y = 1; y < blockList.size() - 1; y++) {
            List<ElementalBondsBlock> elementalBondsBlockList = blockList.get(y);
            for (int x = 1; x < elementalBondsBlockList.size() - 1; x++) {
                elementalBondsBlockSet.add(elementalBondsBlockList.get(x));
            }
        }

        // 获取已有边框的格子，排除周边位置
        for (Map<Integer, ElementalBondsBlock> elementalBondsBlockMap : elementalBondsGameData.getFrameMap().values()) {
            for (ElementalBondsBlock elementalBondsBlock : elementalBondsBlockMap.values()) {
                removeNearbyBlock(blockList, elementalBondsBlockSet, elementalBondsBlock.getX(), elementalBondsBlock.getY());
            }
        }

        // 开始随机
        List<ElementalBondsBlock> randomElementalBondsBlockList = new ArrayList<>();
        for (int i = 0; i < num && !elementalBondsBlockSet.isEmpty(); i++) {
            List<ElementalBondsBlock> elementalBondsBlockList = new ArrayList<>(elementalBondsBlockSet);
            int index = random.nextInt(elementalBondsBlockList.size());
            ElementalBondsBlock elementalBondsBlock = elementalBondsBlockList.get(index);
            randomElementalBondsBlockList.add(elementalBondsBlock);
            removeNearbyBlock(blockList, elementalBondsBlockSet, elementalBondsBlock.getX(), elementalBondsBlock.getY());
        }

        return randomElementalBondsBlockList;
    }

    public static void removeNearbyBlock(List<List<ElementalBondsBlock>> blockList, Set<ElementalBondsBlock> elementalBondsBlockSet, int tmpX, int tmpY) {
        for (int y = tmpY - 1; y <= tmpY + 1; y++) {
            for (int x = tmpX - 1; x <= tmpX + 1; x++) {
                if (ElementalBondsBlockLogic.exist(blockList, x, y)) {
                    elementalBondsBlockSet.remove(blockList.get(y).get(x));
                }
            }
        }
    }

}
